<?php
namespace app\admin\controller;

use app\admin\service\User;
use think\Db;
use think\Validate;

class Login extends Base
{
    public function _initialize()
    {
        $this->assign([
            'head_conf' => $this->head_conf,
        ]);
        $this->userdata = session('userdata');

        if(!empty($this->userdata)){
            $this->redirect('home/index');
        }
    }

    /**
     * 登录界面
     * @return mixed
     */
    public function index(){
        if($this->request->isPost()){
            $data = [
                'username' => input('post.username',''),
                'password' => input('post.password','')
            ];
            $regs = [
                'password' => '/^\S{6,32}$/'
            ];
            $validata = new Validate($regs);
            if(!$validata->check($data)){
                ret('','参数错误');
            }
            $userService = new User();
            $re =$userService->login($data['username'],$data['password']);

            if($re === true){
                ret('','登录成功',true);
            }
            ret('',$re);

        }
		$this->view->engine->layout(false); 
        return $this->fetch();
    }

    /**
     * 注销
     */
    public function logout(){
        session('userdata','');
        session_unset('userdata');
        $this->success('注销成功!','Login/index');

    }

    /**
     * 管理员注册
     */
    public function register(){
        $data = [
            'username' => input('post.username',''),
            'password' => input('post.password','')
        ];
        $regs = [
            'password' => '/^\S{6,32}$/'
        ];
        $validata = new Validate($regs);
        if(!$validata->check($data)){
            ret('','参数错误');
        }

        $re = model('User','Service')->register($data['username'],$data['password']);

        if($re === true){
            ret('','注册成功',true);
        }
        ret('',$re);
    }


}
